package game

import (
	"context"
	"github.com/tianjigames/fairy/constants"
	"github.com/tianjigames/fairy/manager"
	"github.com/tianjigames/fairy/model"
	protos2 "github.com/tianjigames/fairy/protos"
	"github.com/topfreegames/pitaya/component"
	constants2 "github.com/topfreegames/pitaya/constants"
	"github.com/topfreegames/pitaya/logger"
)

/**
组队处理器
 */
type TeamHandler struct {
	component.Base
}

func NewTeamHandler() *TeamHandler {
	return &TeamHandler{}
}

/**
队伍中的某个玩家状态更改处理
 */
func (p *TeamHandler) Result(ctx context.Context,req *protos2.WGTeamResult) (*protos2.GWTeamResultRet,error) {
	player := manager.PlayerManager.GetOnLinePlayerByPlayerId(int(req.PlayerId))
	if player == nil {
		logger.Log.Debugf("[TeamHandler] Result session:%d is closed",req.PlayerId)
		return nil,constants2.ErrReturnNil
	}

	switch req.ResultType {
	case int32(protos2.TeamOperType_TOT_SELFBEQUIT):
	case int32(protos2.TeamOperType_TOT_SELFQUIT):
	case int32(protos2.TeamOperType_TOT_DISMISS):
		err := manager.PlayerManager.SetPlayerObjectTeamInfo(player,nil,false)
		if err != nil {
			logger.Log.Errorf("[Game-TeamHandler] Result failed,error:%s",err.Error())
			return nil,err
		}

		err = manager.PlayerManager.SendPacket(player,&model.MsgData{
			Route: constants.GCRespLeaveTeam,
			Msg: &protos2.GCRespLeaveTeam{
				Type: req.ResultType - 20,
			},
		})

		if err != nil {
			logger.Log.Errorf("[Game-TeamHandler] Result failed,error:%s",err.Error())
			return nil,err
		}
	case int32(protos2.TeamOperType_TOT_CREATE):
	case int32(protos2.TeamOperType_TOT_ENTER):
		err := manager.PlayerManager.SetPlayerObjectTeamInfo(player,nil,req.ResultType == int32(protos2.TeamOperType_TOT_CREATE))
		if err != nil {
			logger.Log.Errorf("[Game_TeamHandler] result failed,error:%s",err)
			return nil,err
		}

		err = manager.PlayerManager.SendPacket(player,&model.MsgData{
			Route: constants.GCEnterTeamRetRoute,
			Msg: &protos2.GCEnterTeamRet{
				Type: req.ResultType,
				TeamInfo: player.TeamInfo,
			},
		})

		if err != nil {
			logger.Log.Errorf("[Game-TeamHandler] Result failed,error:%s",err.Error())
			return nil,err
		}
	}


	return nil,nil
}

/**
解散队伍处理
 */
func (p *TeamHandler) Dismiss(ctx context.Context,req *protos2.WGTeamDismiss) (*protos2.GWTeamDismissRet,error) {
	return nil,nil
}
